package com.adam.example.newssearches8_2_0.script;

import com.adam.example.newssearches8_2_0.Application;
import com.adam.example.newssearches8_2_0.po.NewsPO;
import com.adam.example.newssearches8_2_0.service.EsService;
import com.adam.example.newssearches8_2_0.service.NewsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class ImportDataScript {

    private static final Logger logger = LoggerFactory.getLogger(ImportDataScript.class);
    private static final int BATCH_SIZE = 100;

    @Autowired
    private NewsService newsService;
    @Autowired
    private EsService esService;

    public static void main(String[] args) {
        final ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);
        final ImportDataScript self = applicationContext.getBean(ImportDataScript.class);
//        List<NewsPO> newsPOList = self.newsService.queryByPage(0, 10);
//        logger.debug("newsList {}", newsPOList);
        long start = System.currentTimeMillis();
        boolean indexExists = self.esService.newsIndexExists();
        logger.info("检查索引是否存在：" + indexExists);
        if(indexExists) {
            boolean indexDelete = self.esService.deleteNewsIndex();
            logger.info("删除索引结果：" + indexDelete);
        }
        boolean indexCreate = self.esService.createNewsIndex();
        logger.info("创建索引结果：" + indexCreate);

        long totalCount = self.newsService.queryCount();
        logger.info("MySQL数据行数：" + totalCount);
        int totalBatches = (int) Math.ceil(1.0 * totalCount / BATCH_SIZE);
        for(int i=0;i<totalBatches;i++) {
            int pageNo = i;
            List<NewsPO> newsPOList = self.newsService.queryByPage(pageNo, BATCH_SIZE);
            logger.info("批次[{}]从MySQL获取到{}条数据", i, newsPOList.size());
            boolean result = self.esService.saveNews(newsPOList);
            logger.info("存储到ES：{}", result ? "成功" : "失败");
        }

        long end = System.currentTimeMillis();
        logger.info("任务结束，共耗时{}秒", (end - start) * 1.0 / 1000);
    }

}
